package com.hbx.platform.org.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.hbx.platform.base.annotation.AutoPermission;
import com.hbx.platform.org.domain.Department;
import com.hbx.platform.org.domain.Employee;
import com.hbx.platform.org.query.EmployeeQuery;
import com.hbx.platform.org.service.IDepartmentService;
import com.hbx.platform.org.service.IEmployeeService;
import com.hbx.platform.base.utils.AjaxResult;
import com.hbx.platform.base.utils.PageList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author: hbx
 * @date: 2024/03/30
 **/
@RestController
@RequestMapping("/emp")
@Api(value = "员工的API",description = "员工的CRUD")
@AutoPermission(name = "员工管理")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @GetMapping
    public AjaxResult getAll(){
        try {
            List<Employee> list = employeeService.getAll();
            return AjaxResult.me().setData(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("报错："+e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public AjaxResult queryById(@PathVariable("id") Long id){
        try {
            Employee employee = employeeService.queryById(id);
            return AjaxResult.me().setData(employee);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("报错："+e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @AutoPermission(name = "删除员工",desc = "根据id删除单条记录")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.me().setMessage("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("报错："+e.getMessage());
        }
    }

    @PutMapping
    @ApiOperation("id为null添加，反之修改")
    @AutoPermission(name = "添加或修改员工",desc = "id为null添加，反之修改")
    public AjaxResult saveOrUpdate(@RequestBody @ApiParam("员工对象") Employee employee){
        try {
            if(employee.getId() == null){
                employeeService.save(employee);
                return AjaxResult.me().setMessage("添加成功");
            }else{
                employeeService.update(employee);
                return AjaxResult.me().setMessage("修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("报错："+e.getMessage());
        }
    }

    /**
     * 分页
     * @param query
     * @return
     */
    @PostMapping
    public AjaxResult page(@RequestBody EmployeeQuery query){
        try {
            PageList list = employeeService.page(query);
            return AjaxResult.me().setData(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询分页失败");
        }
    }

    @PatchMapping
    @AutoPermission(name = "批量删除员工",desc = "批量删除")
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            Integer count = employeeService.batchDelete(ids);
            return AjaxResult.me().setMessage("删除了"+count+"条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量删除失败");
        }
    }

    //导入Excel
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile excelFile){
        try {
            ImportParams params = new ImportParams();
            params.setTitleRows(1); //设置1级标题行为一行
            params.setHeadRows(1); //设置header标题行为一行
            List<Employee> errors = new ArrayList<>();
            List<Employee> list = ExcelImportUtil.importExcel(excelFile.getInputStream(), Employee.class, params);
            for (Employee employee : list) {
                String name = employee.getDepartment().getName();
                if(employee.getUsername() == null || employee.getPassword() == null){
                    errors.add(employee);
                    continue;
                }
                Department department = departmentService.queryByName(name);
                employee.setDepartment(department);
                employeeService.save(employee);
            }

            if(errors.size() > 0){
                //将错误的员工信息输出
                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("错误的用户", "erroe"), Employee.class, errors);
                FileOutputStream outputStream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\error.xls");
                workbook.write(outputStream);

                outputStream.close();
                workbook.close();
                return AjaxResult.me().setData(errors).setSuccess(false).setMessage("存在不合格数据");
            }
            return AjaxResult.me().setMessage("导入Excel成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("导入Excel失败");
        }
    }

    //导出Excel
    @PostMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response,@RequestBody EmployeeQuery query){
        PageList<Employee> list = employeeService.page(query);
        //生成输出模板
        ExportParams params = new ExportParams("员工表", "sheet1", ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list.getPageList());
        if(workbook==null){
            return ;
        }
        // 重置响应对象
        response.reset();
        // 当前日期，用于导出文件名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        // 指定下载的文件名--设置响应头
        //设置输出的文件名
        response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xls");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");

        //使用后端跨域后，该方法要添加以下头信息
        response.addHeader("Access-Control-Allow-Credentials","true");
        response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
//        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
//        response.addHeader("Access-Control-Allow-Headers", "Content-Type");

        response.setDateHeader("Expires", 0);
        // 写出数据输出流到页面
        try {
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
